<script setup>
import { useAddEditHook } from '@/hooks/crud/index.js'
import { useColumnsDict, useCommonConfig } from './hook.js'
import { useFormConfigHook } from '@/hooks/usePlusConfigHook.js'
import { roleMenuTreeselect, treeselect } from '@/api/system/menu'
const { proxy,  primaryKey,apiFn, moduleName } = useCommonConfig()
const emit = defineEmits(['refreshList'])

// 表单初始化数据
const initForm = {
  roleId: undefined,
  roleName: undefined,
  roleKey: undefined,
  roleSort: 0,
  status: '0',
  menuIds: [],
  deptIds: [],
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: undefined
}
const rules = {
  roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
  roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
  roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }]
}

/** 查询菜单树结构 */
const menuOptions = ref([])
function getMenuTreeSelect() {
  treeselect().then(({ data }) => {
    console.log('menuOptions', data)
    menuOptions.value = data
  })
}

// 钩子函数
const handlerConfig = {
  beforeOpenFn: (data) => {
    // 新增的时候获取一下菜单树结构
    !data && getMenuTreeSelect()
    return data
  },
  afterOpenFn: async (data) => {
    if(!data) return
    await nextTick()
    getRoleMenuTreeSelect(data.roleId).then((res)=>{
      res.checkedKeys.forEach((v) => {
        nextTick(() => menuRef.value.setChecked(v, true, false))
      })
    })
  },
  beforeInfoFn: (reqData) => {
    return reqData[[primaryKey]]
  },
  afterInfoFn: (resData) => {
    resData.roleSort = Number(resData.roleSort)
    return resData
  },

  beforeSubmitFn: (reqData) => {
    reqData.menuIds = getMenuAllCheckedKeys()
    return reqData
  },
  afterSubmitFn: (resData) => {
    emit('refreshList')
    return resData
  },
  beforeCloseFn: () => {
    menuRef.value &&  menuRef.value.setCheckedKeys([])
    menuExpand.value = false
    menuNodeAll.value = false
    return true
  },
  afterCloseFn: () => {}
}

const { gOpen, gAllExposeOption,gVisible,gFormInstance,gFormData, gIsEdit  } = useAddEditHook({
  moduleName,
  primaryKey,
  initForm,
  rules,
  apiFnConfig:apiFn.apiFnConfig,
  handlerConfig
})

const { gDialogConfig,  gFormConfig} = useFormConfigHook(gAllExposeOption,{
  dialogConfig:{
  },
  formConfig:{
    labelWidth: 120,
  }
});
const {  dictData,  columns, } = useColumnsDict(true,gFormData);

const menuExpand = ref(false)
const menuRef = ref(null)
const menuNodeAll = ref(false)

/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeSelect(roleId) {
  return roleMenuTreeselect(roleId).then(({ data}) => {
    menuOptions.value = data.menus
    return data
  })
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys()
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value) {
  let treeList = menuOptions.value
  for (let i = 0; i < treeList.length; i++) {
    menuRef.value.store.nodesMap[treeList[i].id].expanded = value
  }
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value) {
  menuRef.value.setCheckedNodes(value ? menuOptions.value : [])
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value) {
  gFormData.value.menuCheckStrictly = !!value
}


// 暴露
defineExpose({ gOpen })
</script>
<template>
  <PlusDialog v-model="gVisible" v-bind="gDialogConfig">
    <PlusForm ref="gFormInstance" v-model="gFormData" :columns="columns" v-bind="gFormConfig">
      <template #plus-field-menuScope>
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
        <el-checkbox v-model="gFormData.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
        <el-tree
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          ref="menuRef"
          node-key="id"
          :check-strictly="!gFormData.menuCheckStrictly"
          empty-text="加载中，请稍候"
          :props="{ label: 'label', children: 'children' }"
        />
      </template>
    </PlusForm>
  </PlusDialog>
</template>
<style lang="scss" scoped></style>
